﻿namespace BrowserCacheBusting
{
    using System;
    using System.Collections.Generic;
    using System.Configuration;
    using System.IO;
    using System.Linq;
    using BrowserCacheBustingUtilities;

    class Program
    {
        static void Main(string[] arguments)
        {
            bool appSettingsDefined = ConfigurationManager.AppSettings.AllKeys.Any(key => !string.IsNullOrWhiteSpace(ConfigurationManager.AppSettings[key]));

            if (((arguments.Length == 0 && !appSettingsDefined) || (arguments.Length == 1 && (arguments[0] == "?" || arguments[0] == "/?"))))
            {
                Console.WriteLine();
                Console.Write(CacheBuster.GetConsoleArguments());

                if (arguments.Length > 1)
                    Console.ReadLine();

                Environment.Exit(0);
            }

            string filePath = GetExecutingFilePath();
            DirectoryInfo directory = new DirectoryInfo(filePath);
            CacheBuster.ApplicationPath = directory;
            List<string> errors = CacheBuster.ProcessCommandLineArguments(arguments);

            if (errors.Count > 0)
            {
                Console.WriteLine();
                Console.WriteLine("Required arguments have not been specified.");

                foreach (string error in errors)
                    Console.WriteLine("* " + error);

                Environment.Exit(1);
            }

            try
            {
                CacheBuster.Go();
            }
            catch (Exception ex)
            {
                Console.WriteLine("An unexpected error occuring while cache busting: {0}.", ex.Message);
                Environment.Exit(1);
            }

            Environment.Exit(0);
        }

        private static string GetExecutingFilePath()
        {
            string filePath = System.Reflection.Assembly.GetExecutingAssembly().CodeBase;

            if (filePath.StartsWith("file:///"))
                filePath = filePath.Substring(8);

            filePath = filePath.Replace("/", @"\");
            return filePath.Substring(0, filePath.LastIndexOf(@"\") + 1);
        }
    }
}
